package com.app.couponsharelife.ui.main.tribe

import android.annotation.SuppressLint
import android.content.Intent
import android.media.AudioManager
import android.media.SoundPool
import android.os.Bundle
import android.view.View
import androidx.constraintlayout.widget.ConstraintLayout
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import com.hwangjr.rxbus.annotation.Subscribe
import com.hwangjr.rxbus.annotation.Tag
import com.hwangjr.rxbus.thread.EventThread
import com.app.couponsharelife.R
import com.app.couponsharelife.base.LazyFragment
import com.app.couponsharelife.data.bean.CouponMoneyBean
import com.app.couponsharelife.databinding.FragmentTribeBinding
import com.app.couponsharelife.manage.Contacts
import com.app.couponsharelife.ui.adapter.TribeListAdapter
import com.app.couponsharelife.ui.listener.OnClickListener
import com.app.couponsharelife.ui.main.MainActivity
import com.app.couponsharelife.ui.main.me.invite.ShareInvitePicActivity
import com.app.couponsharelife.ui.main.tribe.checkin.CheckInActivity
import com.app.couponsharelife.ui.main.tribe.couponworkshop.CouponWorkShopActivity
import com.app.couponsharelife.ui.main.tribe.force.CouponForceActivity
import com.app.couponsharelife.ui.main.tribe.money.CouponMoneyActivity
import com.app.couponsharelife.ui.viewmodel.TribeViewModel
import com.app.couponsharelife.utils.AppUtils
import com.app.couponsharelife.utils.Transformer
import com.app.fuquan.data.bean.PageStatus
import github.hellocsl.layoutmanager.gallery.GalleryLayoutManager
import kotlinx.android.synthetic.main.fragment_tribe.*
import java.math.BigDecimal
import java.util.HashMap

/**
 * Created by guluwa on 2018/11/21.
 */
class TribeFragment : LazyFragment() {
    override val viewLayoutId: Int get() = R.layout.fragment_tribe
    private var mViewModel: TribeViewModel? = null
    private var lastId = ""
    private var mSoundPool: SoundPool? = null//音效
    private var mVoice: Int = 0
    private var isFirst = true
    private var quanPrice=""
    private var quanValue=""
    companion object {
        fun newInstance(): TribeFragment {
            val fragment = TribeFragment()
            fragment.arguments = Bundle()
            return fragment
        }
    }

    override fun initViews() {
        initClickEvent()
        initRecyclerView()
        initVoice()
    }
    private fun initVoice() {
        //初始化SoundPool
        mSoundPool = SoundPool(1, AudioManager.STREAM_SYSTEM, 5)
        mVoice = mSoundPool!!.load(activity, R.raw.buluo, 1)
    }
    private fun initClickEvent() {
        (mViewDataBinding as FragmentTribeBinding).listener = View.OnClickListener {
            when (it.id) {
                R.id.clMoney -> {
                    val intent = Intent(context, CouponMoneyActivity::class.java)
                    intent.putExtra("money", tvMoney.text.toString())
                    startActivity(intent)
                }
                R.id.clDiamond -> {
                    val intent = Intent(context, CouponForceActivity::class.java)
                    intent.putExtra("force", tvDiamond.text.toString())
                    startActivity(intent)
                }
                R.id.ivTribePlanet, R.id.ivPlanetArrow -> {
                    var intent=Intent(context, CouponWorkShopActivity::class.java)
                    intent.putExtra("QuanPrice",quanPrice)
                    intent.putExtra("QuanValue",quanValue)
                    startActivity(intent)
                }
            }
        }
    }

    private fun initRecyclerView() {
        //计算位置
        val heightPixels = AppUtils.getDisplayMetrics(activity!!).heightPixels * 0.925
        val widthPixels = AppUtils.getDisplayMetrics(activity!!).widthPixels
        val layoutParams = ConstraintLayout.LayoutParams(ConstraintLayout.LayoutParams.MATCH_PARENT, 0)
        if (0.675 * heightPixels > (0.057 * heightPixels + widthPixels * 1.257 * 0.765)) {
            layoutParams.bottomToBottom = R.id.mGuideLineViewPagerBottom
            layoutParams.topToTop = R.id.mGuideLineViewPagerTop
        } else {
            layoutParams.topToBottom = R.id.mTopBg
            layoutParams.topMargin = AppUtils.dip2px(context!!, 10f)
            layoutParams.bottomToBottom = R.id.mGuideLineViewPagerBottom
        }
        mRecyclerView.layoutParams = layoutParams
        //初始化
        if (isFirst) {
            isFirst = false
            val layoutManager = GalleryLayoutManager(GalleryLayoutManager.HORIZONTAL)
            layoutManager.attach(mRecyclerView, 1)
            layoutManager.setItemTransformer(Transformer())
            mRecyclerView.layoutManager = layoutManager
            mRecyclerView.adapter = TribeListAdapter(object : OnClickListener {
                override fun click(arg1: Int, arg2: Any) {
                    when (arg2) {
                        "每日分享" -> {
                            if (activity is MainActivity) {
                                (activity as MainActivity).scrollToPage(3)
                            }else{
                                val intent=Intent(context,MainActivity::class.java)
                                intent.putExtra("Type","TribeFragment")
                                intent.putExtra("Status","TribeFragment")
                                startActivity(intent)
                                activity!!.finish()
                            }
                        }
                        "每日签到" -> startActivity(Intent(context, CheckInActivity::class.java))
                        "邀请好友" -> startActivity(Intent(context, ShareInvitePicActivity::class.java))
                    }
                }
            })
        }
    }

    @SuppressLint("SetTextI18n")
    private fun initDiamonds(data: List<Any>) {
        mDiamondContainer.post {
            if (data.isNotEmpty())
                mDiamondContainer.setData(data, 1)
            else
                mDiamondContainer.setData(arrayListOf(data), 0)
        }
        mDiamondContainer.listener = object : OnClickListener {
            override fun click(arg1: Int, arg2: Any) {
                mSoundPool!!.play(mVoice, 1f, 1f, 0, 0, 1f)
                if (arg1 == -1) {
                    showToastMsg(arg2 as String)
                } else {
                    if (lastId != (arg2 as CouponMoneyBean.ListBean).index) {
                        mDiamondContainer.canClick = false
                        lastId = arg2.index
                        addCouponKing(arg2.index)
                        tvMoney.text = BigDecimal(tvMoney.text.toString().toDouble())
                                .add(BigDecimal(arg2.value))
                                .setScale(5, BigDecimal.ROUND_HALF_UP)
                                .toString()
                    }
                }
            }
        }
    }

    override fun initViewModel() {
        if (mViewModel == null) mViewModel = ViewModelProviders.of(this).get(TribeViewModel::class.java)
        if (!mViewModel!!.getCouponKing()!!.hasObservers()) {
            mViewModel!!.getCouponKing()!!.observe(this, Observer {
                if (it == null) {
                    dismissProgressDialog()
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
//                        showProgressDialog("请稍候")
                    }
                    PageStatus.Error -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshGetCouponKing(hashMapOf(), false)
                        showToastMsg((parseErrorDate(it.error!!.message).tip))
                    }
                    PageStatus.Empty -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshGetCouponKing(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        dismissProgressDialog()
                        mViewModel!!.refreshGetCouponKing(hashMapOf(), false)
                        if (it.data!!.code == 200 && it.data.data != null) {
                            quanPrice=it.data.data!!.couponKing
                            quanValue=it.data.data!!.couponForce
                            tvMoney.text = it.data.data!!.couponKing
                            tvDiamond.text = it.data.data!!.couponForce
                            initDiamonds(it.data.data!!.list)
                        } else {
                            showToastMsg("获取失败")
                        }
                    }
                }
            })
            mViewModel!!.addCouponKing()!!.observe(this, Observer {
                if (it == null) {
                    mDiamondContainer.canClick = true
                    showToastMsg("数据出错啦")
                    return@Observer
                }
                when (it.status) {
                    PageStatus.Loading -> {
                    }
                    PageStatus.Error -> {
                        mDiamondContainer.canClick = true
                        mViewModel!!.refreshAddCouponKing(hashMapOf(), false)
                        showToastMsg((parseErrorDate(it.error!!.message).tip))
                    }
                    PageStatus.Empty -> {
                        mDiamondContainer.canClick = true
                        mViewModel!!.refreshAddCouponKing(hashMapOf(), false)
                        showToastMsg("数据出错啦")
                    }
                    PageStatus.Content -> {
                        mDiamondContainer.canClick = true
                        mViewModel!!.refreshAddCouponKing(hashMapOf(), false)
                        if (it.data!!.code == 200) {

                        } else {
                            showToastMsg("领取失败")
                        }
                    }
                }
            })
        }
    }

    override fun lazyLoad() {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        mViewModel?.refreshGetCouponKing(map, true)
    }

    private fun addCouponKing(index: String) {
        val map = HashMap<String, String>()
        map["userId"] = AppUtils.getString(Contacts.USERID, "")
        map["index"] = index
        map["timestamp"] = System.currentTimeMillis().toString()
        map["sign"] = AppUtils.getMapString(map)
        mViewModel?.refreshAddCouponKing(map, true)
    }

    override fun onRestoreState(savedInstanceState: Bundle) {
        super.onRestoreState(savedInstanceState)
        lazyLoad()
    }
    @Subscribe(thread = EventThread.MAIN_THREAD, tags = [(Tag("freshCouponKing"))])
    fun receiveData(fresh: String) {
        lazyLoad()
    }
}